package lion.dev.encrypt;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;

/**
 * 原理为 使用一个密钥对数据进行摘要，将这个密钥告诉对方，把摘要和数据发送给对方， 　 　然后让对方跟据密钥来验证数据完整性
 *
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-12-27
 */
public class HmacMD5 {

	public static final String ALGORITHM = "HmacMD5";

	public String generateKey(String seed) {

		// 生成key的时候可以加密
		KeyGenerator keyGenerator = null;
		try {
			keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalArgumentException("", e);
		}
		SecureRandom sr = null;
		if (StringUtils.isNotBlank(seed)) {
			sr = new SecureRandom(seed.getBytes(Charsets.UTF_8));
		} else {
			sr = new SecureRandom();
		}
		keyGenerator.init(sr);

		return Base64.encodeBase64String(keyGenerator.generateKey().getEncoded());
	}

	public byte[] digest(byte[] data, String key) {

		SecretKey secretKey = new SecretKeySpec(Base64.decodeBase64(key), ALGORITHM);
		Mac mac = null;
		try {
			mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
		} catch (Exception e) {
			throw new IllegalArgumentException("", e);
		}

		return mac.doFinal(data);
	}

	public byte[] digest(String data, String key) {

		return digest(data.getBytes(Charsets.UTF_8), key);
	}

	public String digestString(byte[] data, String key) {

		return new String(digest(data, key), Charsets.UTF_8);
	}

	public String digestString(String data, String key) {

		return digestString(data.getBytes(Charsets.UTF_8), key);
	}

	public static void main(String[] args) {

		HmacMD5 hmac = new HmacMD5();
		String src = "中华人民共和国";

		String key = hmac.generateKey(null);
		System.out.println("KEY:" + key);

		System.out.println("摘要");
		System.out.println(Hex.encodeHexString(hmac.digest(src.getBytes(), key)));

	}
}
